import React , { Component } from 'react';
import {message, Modal,Tooltip } from 'antd';
import {connect} from 'react-redux';
// import {getCurvesIntoDaoShow,getDepthShow} from '../../../redux/actions';
import SelectFileForm1 from '../../../components/Modal/select-file-form1';
import {reqgetOrigindata,reqSaveOrigindata} from '../../../api';
import EditableTable from './original/EditableTable';
import {setOriginData,setDocInReducer} from '../../../redux/actions'

import ExportJsonExcel from 'js-export-excel';


 
class OriginalData extends Component {

  state = {
    visible: '0',
    doc_id: '',   // 存储文件id
    drill_id:'',
    org_id:'',
    ws_id:''
  }
  
  openFileShow = () => {    // 添加数据文件 弹框显示
    this.setState({
      visible: '1'
    });
  };
  handleOpenFile = async() => {    // 添加数据文件 响应函数 
    this.setState({ visible: '0'});
    this.setState({ visible: '0'});
    var docInfo;
    const doc_id = this.formRef.current.getFieldValue('doc_id');
    this.docList.map((item) => {
      if(item.doc_id === doc_id){
        docInfo = item
      }
    });
    // this.setState({
    //   docInfo
    // });
    const drill_id = docInfo.drill_id;
    const org_id = docInfo.org_id;
    const ws_id = docInfo.ws_id;
    this.setState({
      doc_id,   // 存储文件id
      drill_id,
      org_id,
      ws_id
    })
    
    // console.log("选择文件成功11111111111111111111111111",ws_id,org_id,drill_id,doc_id);
    const result = await  reqgetOrigindata(ws_id,org_id,drill_id,doc_id);    // 获取文件 数据
    if(result.code===200){
      const docData = result.data.data_set;
      // console.log('111111111111111');
      // console.log('收到的原始数据',result.data.data_set);
      this.setState({
        docdata:docData,
      })
      this.props.setDocInReducer(result.data);
      this.props.setOriginData(result.data.data_set,result.data.header)
    }else{
      message.error('获取失败');
    }
   

 
  }; 
  // saveDocDataShow=()=>{ // 保存文件 弹框显示
  //   this.setState({
  //     visible:'2'
  //   })
  // }

  saveDocDataShow = async() => {    // 保存文件 响应函数    
    // this.setState({ visible: '0'});
   //data_set,doc_id,drill_id,org_id,ws_id
   const doc_id=this.state.doc_id;
   const drill_id=this.state.drill_id;
   const org_id=this.state.org_id;
   const ws_id=this.state.ws_id;
   let docdata=this.props.OriginData.originData;
    if(docdata){
      docdata.map((item)=>{
        delete item.key;
      })//docdata为传送给后台的数据
      let res=await reqSaveOrigindata(docdata,doc_id,drill_id,org_id,ws_id);
      console.log(res);
      message.success('保存成功');
    }
  }; 
  // handlesaveAnoDocData=async()=>{    //另存为文件
  //   let docdata=this.data;
  //   docdata.map((item)=>{
  //     delete item.key;
  //   })//docdata为传送给后台的数据
  //   this.setState({ visible: '0'});
  //   const doc_name = this.formRef.current.getFieldValue('doc_name');
  //   const doc_id = this.state.docId;
  //   const saveType='another_save';
  //   reqSaveOrigindata(saveType,doc_id,doc_name,docdata);
  // }

  handleCancel = () => {    // 对话框取消按钮
    this.formRef.current.resetFields();
    this.setState({
      visible: '0'
    });   
  };

  // handlesaveDocPic = async() => {    // 另存为图片   vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
  //   const newCanvas = document.createElement("canvas");
  //   const element = document.querySelector('.content');

  //   const dom_width = parseInt(window.getComputedStyle(element).width);
  //   const dom_height = parseInt(window.getComputedStyle(element).height);
  //   console.log(dom_width)
  //   console.log(dom_height)
  //   //将canvas画布放大若干倍，然后盛放在较小的容器内，就显得不模糊了
  //   newCanvas.width = dom_width * 2;
  //   newCanvas.height = dom_height * 2;
  //   newCanvas.style.width = dom_width + "px";
  //   newCanvas.style.height = dom_height + "px";
  //   const context = newCanvas.getContext("2d");
  //   context.scale(1.8, 1.8);

  //   html2canvas(element, { canvas: newCanvas }).then((canvas) => {
  //       const imgUri = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream"); // 获取生成的图片的url
  //       const base64ToBlob = (code) => {
  //           let parts = code.split(';base64,');
  //           let contentType = parts[0].split(':')[1];
  //           let raw = window.atob(parts[1]);  // let raw = window.atob(parts[1]);
  //           let rawLength = raw.length;
      
  //           let uInt8Array = new Uint8Array(rawLength);
      
  //           for (let i = 0; i < rawLength; ++i) {
  //             uInt8Array[i] = raw.charCodeAt(i);
  //           }
  //           return new Blob([uInt8Array], {type: contentType});
  //       };
  //       const blob = base64ToBlob(imgUri);
  //       // window.location.href = imgUri; // 下载图片
  //       // 利用createObjectURL，模拟文件下载
  //       const fileName = '原始数据.png';
  //       if (window.navigator.msSaveOrOpenBlob) {
  //           navigator.msSaveBlob(blob, fileName);
  //       } else {
  //           const blobURL = window.URL.createObjectURL(blob)
  //           const vlink = document.createElement('a');
  //           vlink.style.display = 'none';
  //           vlink.href = blobURL;
  //           vlink.setAttribute('download', fileName);

  //           if (typeof vlink.download === 'undefined') {
  //               vlink.setAttribute('target', '_blank');
  //           }

  //           document.body.appendChild(vlink);

  //           var evt = document.createEvent("MouseEvents");
  //           evt.initEvent("click", false, false);
  //           vlink.dispatchEvent(evt);

  //           document.body.removeChild(vlink);
  //           window.URL.revokeObjectURL(blobURL);
  //       }
  //   }); 
  // }; 
  downloadTable2Execel=()=>{
    const data = this.props.OriginData.originData ? this.props.OriginData.originData : '';//表格数据
    // console.log(data);
    var option={};
    let fileName=this.props.docData ? this.props.docData.doc_name.split(".")[0] : "";
    option.fileName = fileName+'_原始数据'
    let header=this.props.OriginData.header;
    let strArr=Object.keys(data[0]); //存储表头的英文

    //删除无用列，后端处理返回数据后可以注释
    let index1=strArr.indexOf('deleted');
    strArr.splice(index1,1);
    let index2=strArr.indexOf('key');
    strArr.splice(index2,1);

    console.log(strArr)
    option.datas=[
      {
        sheetData:data,
        sheetName:'sheet',
        sheetFilter:strArr,
        sheetHeader:header,
      }
    ];
  
    var toExcel = new ExportJsonExcel(option); 
    toExcel.saveExcel();    
  }
  changeAddRow=()=>{
    if(this.state.addrow===true)
    {this.setState({
      addrow:false
    })}else{
      this.setState({
        addrow:true
      })
    }
  }

  render() {
    const {visible,docdata} = this.state;
    const fileData = this.fileData || {};
    return (
      
      <div className="depth-two-dim-wrapper" style={{background:'#fff'}}>
        <div className="button-title">
          {/* <ShowHeader /> */}
          <div className="show-header-wrapper" >
            <Tooltip placement="bottom" title='文件' overlayStyle={{fontSize:12}}>    
              <i className="iconfont icon" onClick={this.openFileShow} style={{fontSize:15}}>&#xe613;</i>
            </Tooltip>
            <Tooltip placement="bottom" title='保存' overlayStyle={{fontSize:12}}>
              <i className="iconfont icon" onClick={this.saveDocDataShow} style={{fontSize:19}}>&#xe936;</i> 
            </Tooltip>
            {/* <Tooltip placement="bottom" title='另存为' overlayStyle={{fontSize:12}}>
              <i className="iconfont icon" onClick={this.saveAnoDocDataShow} style={{fontSize:15}}>&#xe606;</i> 
            </Tooltip> */}
            <Tooltip placement="bottom" title='导出为Excel' overlayStyle={{fontSize:12}}>
              <i className="iconfont icon" onClick={this.downloadTable2Execel}>&#xe606;</i>
            </Tooltip>

            <Modal
              title="选择数据文件"
              visible={visible === '1'}
              okText="确定"
              cancelText="取消"
              onOk={this.handleOpenFile}
              onCancel={this.handleCancel}
              destroyOnClose={true}  // 关闭时销毁子元素
            >
              <SelectFileForm1 
                setForm = {(formRef) => {this.formRef = formRef}}
                setDocList = {(docList) => {this.docList = docList}}
              /> 
            </Modal>
            {/* <Modal
              title="保存"
              visible={visible === '2'}
              onOk={this.handlesaveDocData}
              onCancel={this.handleCancel}
            ></Modal> */}
          </div>
          {/* <ShowHeader /> */}
        </div>
        <div className="content show-origindata" style={{overflow:'auto'}}>
          {this.props.docData.doc_id?<EditableTable 
         /> :null} 
        </div>
      </div> 
    )
  }
}

export default connect(
  state => ({docData: state.docData,OriginData:state.OriginData}),
  {setOriginData,setDocInReducer}      
)(OriginalData);




























// import React, { Component } from 'react';
// import Three1 from '../../../components/three/three1';   //
// import Three2 from '../../../components/three/three2';   //
// import Three3 from '../../../components/three/three3';   //
// import Three4 from '../../../components/three/three4';   // 
// import Three5 from '../../../components/three/three5';   // 纹理
// import Three6 from '../../../components/three/three6';   // 管道 实例

 
// class OriginalData extends Component {
//     constructor(props) {
//         super(props);
//         this.state = {  };
//     }
//     render() {
//         return (
//           <div>
//             <Three6 />
//           </div>
//         );
//     }
// }
 
// export default OriginalData;